package com.scholar.goods.controller;

import com.scholar.shop.common.*;
import com.scholar.shop.seller.tags.api.TagsApi;
import com.scholar.shop.seller.tags.domain.AddTagGoodsRequest;
import com.scholar.shop.seller.tags.domain.TagGoodsOpenVO;
import com.scholar.shop.seller.tags.domain.TagsOpenVO;
import com.scholar.shop.seller.tags.domain.TagsPageQueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;

/**
 * 商品标签管理模块
 * @author kimmy
 **/
@RestController
@RequestMapping("/seller/goods/tags")
public class GoodsTagsController {

    private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(GoodsTagsController.class);

    /**
     * 商品标签操作API
     */
    @Autowired
    private TagsApi tagsApi;

    /**
     * 分页查询商品标签
     * @param request 分页查询对象
     * @return 结果集
     * @throws BusinessException 异常信息
     */
    @PostMapping
    public CommonRes<Pages<TagsOpenVO>> listByPageQuery(@RequestBody @Valid TagsPageQueryRequest request,
                                                        BindingResult bindingResult) throws Exception {
        validate(bindingResult);
        return tagsApi.listByPageQuery(request);
    }

    /**
     * 查询指定标签id下的商品et
     * @param tagId 标签id
     * @return 结果集
     * @throws Exception 异常信息
     */
    @GetMapping("/{tagId}/queryGoodsList")
    public CommonRes<Pages<TagGoodsOpenVO>> listTagGoodsList(@PathVariable("tagId") Integer tagId) throws Exception {
        return tagsApi.listTagGoodsList(tagId);
    }

    /**
     * 往指定的标签id下批量添加商品
     * @param request 添加商品请求对象
     * @return 处理结果
     */
    @PutMapping
    public CommonRes<String> addTagGoods(@RequestBody @Valid AddTagGoodsRequest request,
                                       BindingResult bindingResult) throws Exception {
        validate(bindingResult);
        return tagsApi.addTagGoods(request);
    }

    /**
     * 数据校验
     * @param bindingResult 校验结果
     * @throws BusinessException 异常信息
     */
    private void validate(BindingResult bindingResult) throws BusinessException {
        if (bindingResult.hasErrors()) {
            throw new BusinessException(EmBusinessError.SYS_REQUEST_PARAMETER_INVALIDATE,
                    CommonUtil.processErrorString(bindingResult));
        }
    }

}
